package web.get;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.Book;
import domain.User;
import service.BookService;
import service.WordService;
import service.impl.BookServiceImpl;
import service.impl.WordServiceImpl;
import util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/getWord")
public class GetWordServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        Map<String,Object> msg = new HashMap<>(8);
        ObjectMapper om =new ObjectMapper();
        int bid;
        try{
            bid= Integer.parseInt(request.getParameter("book"));
        }catch (Exception e){
            e.printStackTrace();
            bid=-1;
        }
        System.out.println(bid);
        User user = ServletUtil.checkLogin(request);
        if (user==null){
            //未登录或登录信息不对
            msg.put("msg","请登录");
            om.writeValue(response.getOutputStream(),msg);
        }
        if (bid==-1) {
            bid=(int)request.getAttribute("book");
            if(bid==1){
                //未传参,同时也未转发
                msg.put("msg","书籍参数错误");
                om.writeValue(response.getOutputStream(),msg);
            }

        }
        WordService ws = new WordServiceImpl();
        BookService bs = new BookServiceImpl();
        Book book = bs.getBookbybid(bid);
        //user不为空则判断书籍是否对应
        assert user != null;
        assert book != null;
        if(user.getUid()!= book.getUid() && book.getUid()!=0){
            msg.put("msg","无法访问该书籍");
            om.writeValue(response.getOutputStream(),msg);
        }
        msg.put("bookTitle",book.getName());
        msg.put("execute",ws.getExecuteWord(user.getUid()));
        msg.put("familiar",ws.getFamiliarWord(user.getUid()));
        msg.put("word",ws.getWordCollect(bid));
        om.writeValue(response.getOutputStream(),msg);
    }
}
